//
//  WBRefreshControl.swift
//  weibo
//
//  Created by yanghong on 15/12/15.
//  Copyright © 2015年 杨鸿. All rights reserved.
//

import UIKit

let refreshControlHeight: CGFloat = 50
enum WBRefreshControlState: Int {
    case Normal = 0
    case Pulling = 1
    case refreshing = 2
    
}
class WBRefreshControl: UIControl {
    
    //记录下上一次的状态
    var oldRefreshState: WBRefreshControlState = .Normal
    //判断当前控件所处的状态
    //这里的逻辑是重点
    var refreshState: WBRefreshControlState = .Normal {
        
        didSet{
            
            switch refreshState {
                
            case .Pulling :
                msgLabel.text = "放开起飞"
                UIView.animateWithDuration(0.5, animations: { () -> Void in
                    
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                print("松开即可刷新")
            case .refreshing :
                print("正在起飞")
                
                msgLabel.text = "正在加载.."
                arrowIcon.hidden = true
                indicator.startAnimating()
                UIView.animateWithDuration(0.5, animations: { () -> Void in
                    
                    var contentInset = self.scrollView!.contentInset
                    contentInset.top += refreshControlHeight
                    self.scrollView?.contentInset = contentInset
                })
                
               sendActionsForControlEvents(UIControlEvents.ValueChanged)
                
            case .Normal :
                msgLabel.text = "下拉刷新"
                arrowIcon.hidden = false
                indicator.stopAnimating()
                UIView.animateWithDuration(0.5, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformIdentity
                })
                print("下拉刷新")
                
                //判断从刷新状态进入到普通状态
                
                if oldRefreshState == .refreshing {
                    //增加顶部的滑动距离
                    UIView.animateWithDuration(0.5, animations: { () -> Void in
                        
                        var contentInset = self.scrollView!.contentInset
                        contentInset.top -= refreshControlHeight
                        self.scrollView?.contentInset = contentInset
                    })
  
                }
                
            }
            
            oldRefreshState = refreshState
        }
        
    }
    
    var scrollView: UIScrollView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
            setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK -  结束刷新
    
    func endRefresh() {
        
        refreshState = .Normal
        
    }
    private func setupUI() {
        
        backgroundColor = UIColor.redColor()
        
        var frame = self.frame
        frame.size = CGSizeMake(SCREENWIDTH, refreshControlHeight)
        frame.origin.y = -refreshControlHeight
        self.frame = frame
        //添加控件
        
        addSubview(arrowIcon)
        addSubview(msgLabel)
        addSubview(indicator)
        
        //添加约束
        //arrowIcon
        arrowIcon.snp_makeConstraints { (make) -> Void in
            
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-35)
        }
        //msgLabel
        msgLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(arrowIcon)
            make.leading.equalTo(arrowIcon.snp_trailing).offset(5)
            
        }
        //indicator
        indicator.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon)
            
        }
        
    }
   
    //当前控件加载到某个控件上的时候会调用此方法
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        if let scrollView = newSuperview as? UIScrollView {
            
            //利用KVO 监听 newSuperview 的滚动
            
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: [NSKeyValueObservingOptions.New], context: nil)
            
            self.scrollView = scrollView
            
            var frame = self.frame
            
            frame.size.width = scrollView.frame.size.width
            
            self.frame = frame
            
        }
        
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let contentOffsetY = scrollView?.contentOffset.y
        
        let contentInsetTop = scrollView?.contentInset.top ?? 0
        
        let conditionValue = -contentInsetTop - refreshControlHeight
        
        if scrollView!.dragging {
            
            if refreshState == .Normal && contentOffsetY < conditionValue {
                
                refreshState = .Pulling
                
            }else if refreshState == .Pulling && contentOffsetY >= conditionValue {
                
                refreshState = .Normal
                
              }
            }else{
                
                if refreshState == .Pulling {
                    
                    refreshState = .refreshing
                    
            }
        }
    }
    
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
  

    // MARK -  懒加载控件
    //箭头
    private lazy var  arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    private lazy var msgLabel: UILabel = {
        
        let msgLabel = UILabel()
        
        msgLabel.text = "下拉刷新"
        
        msgLabel.textColor = UIColor.darkGrayColor()
        
        msgLabel.font = UIFont.systemFontOfSize(12)
        
        return msgLabel
    }()
    
    // 菊花转
    
    private lazy var indicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    
}
